package com.probox.common.entity.service.wechat.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.PreAuthorizeException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.entity.domain.wechat.WechatAuthorizationInfo;
import com.probox.common.entity.domain.wechat.broadcast.*;
import com.probox.common.entity.domain.wechat.vo.QueryGood;
import com.probox.common.entity.mapper.wechat.WechatBroadcastProductMapper;
import com.probox.common.entity.service.wechat.IWechatBroadcastProductMiddleService;
import com.probox.common.entity.service.wechat.IWechatBroadcastProductService;
import com.probox.common.entity.service.wechat.WechatBroadcastGoodsService;
import com.probox.common.entity.service.wechat.WechatMiniService;
import com.probox.common.entity.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Kite
 * @date 2021/7/9
 */
@Service
@Transactional
public class WechatBroadcastGoodsServiceImpl implements WechatBroadcastGoodsService {

    @Autowired
    private WechatMiniService wechatMiniService;

    @Autowired
    private IWechatBroadcastProductService wechatBroadcastProductService;

    @Autowired
    private IWechatBroadcastProductMiddleService wechatBroadcastProductMiddleService;

    @Autowired
    private WechatBroadcastProductMapper wechatBroadcastProductMapper;

    private final String applet = "applet";

    private final String errcode = "0";

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //添加商品并审核
    private final String ADD_GOOD_URL = "https://api.weixin.qq.com/wxaapi/broadcast/goods/add?access_token=";

    //撤回商品审核
    private final String RESETAUDIT_URL =  "https://api.weixin.qq.com/wxaapi/broadcast/goods/resetaudit?access_token=";

    //重新提交审核
    private final String AUDIT_URL = "https://api.weixin.qq.com/wxaapi/broadcast/goods/audit?access_token=";

    //删除商品
    private final String GOODS_DELETE_URL = "https://api.weixin.qq.com/wxaapi/broadcast/goods/delete?access_token=";

    //更新商品
    private final String GOODS_UPDATE_URL = "https://api.weixin.qq.com/wxaapi/broadcast/goods/update?access_token=";

    //获取商品状态
    private final String GETGOODSWAREHOUSE_URL = "https://api.weixin.qq.com/wxa/business/getgoodswarehouse?access_token=";

    //获取商品列表
    private final String GETAPPROVED_URL ="https://api.weixin.qq.com/wxaapi/broadcast/goods/getapproved?access_token=";

    /**
     * 添加商品并审核
     * @param goodsInfo
     * @return
     */
    @Override
    public boolean addGood(GoodsInfo goodsInfo) {
        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = ADD_GOOD_URL + authorizerAppid.getAuthorizerAccessToken();
        goodsInfo.setUrl("pages/productDetail/productDetail?id="+goodsInfo.getUrl());
        String string = JSONObject.toJSONString(goodsInfo);
        JSONObject jsonObject = JSONObject.parseObject(string);
        jsonObject.remove("imageUrlStr");
        JSONObject object = new JSONObject();
        object.put("goodsInfo",jsonObject);
        object.remove("productId");
        logger.info("添加商品并审核请求参数：{}",object);
        String data = HttpUtil.PostUrl(url, object);
        logger.info("添加商品并审核结果：{}",data);
        jsonObject = JSONObject.parseObject(data);
        String errcode = jsonObject.getString("errcode");
        if (!this.errcode.equals(errcode)){
            if (errcode.equals("300002")){
                throw new PreAuthorizeException("名称长度不符合规则");
            }else if (errcode.equals("300004")){
                throw new PreAuthorizeException("商品名称存在违规违法内容");
            }else if (errcode.equals("300005")){
                throw new PreAuthorizeException("商品图片存在违规违法内容");
            }else if (errcode.equals("300003")){
                throw new PreAuthorizeException("价格输入不合规（如：现价比原价大、传入价格非数字等）");
            }else  if (errcode.equals("300018")){
                throw new PreAuthorizeException("图片高度不能超时300px");
            }
        }else {
            WechatBroadcastProduct wechatBroadcastProduct = new WechatBroadcastProduct();
            BeanUtils.copyProperties(goodsInfo,wechatBroadcastProduct);

            wechatBroadcastProduct.setGoodsId(jsonObject.getLong("goodsId"));
            wechatBroadcastProduct.setAuditId(jsonObject.getLong("auditId"));

            System.out.println("商品数据:"+wechatBroadcastProduct.toString());
            logger.info("商品数据:{}",wechatBroadcastProduct.toString());

            wechatBroadcastProductService.insertWechatBroadcastProduct(wechatBroadcastProduct);
        }


        return this.errcode.equals(jsonObject.getString("errcode"));
    }

    /**
     * 撤回商品审核
     * @param queryGood
     * @return
     */
    @Override
    public boolean resetauditAudit(QueryGood queryGood) {
        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = RESETAUDIT_URL + authorizerAppid.getAuthorizerAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("auditId",queryGood.getAuditId());
        jsonObject.put("goodsId",queryGood.getGoodsId());
        logger.info("撤回商品审核请求参数：{}",jsonObject);
        String data = HttpUtil.PostUrl(url, jsonObject);
        logger.info("添加商品并审核结果：{}",data);
        jsonObject = JSONObject.parseObject(data);
        return errcode.equals(jsonObject.getString("errcode"));
    }

    /**
     * 重新提交审核
     * @param goodsId
     * @return
     */
    @Override
    public boolean submitAudit(Integer goodsId) {
        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = AUDIT_URL + authorizerAppid.getAuthorizerAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsId",goodsId);
        logger.info("重新提交审核请求参数：{}",jsonObject);
        String data = HttpUtil.PostUrl(url, jsonObject);
        logger.info("商品重新提交审核结果：{}",data);
        jsonObject = JSONObject.parseObject(data);
        return errcode.equals(jsonObject.getString("errcode"));
    }

    /**
     * 删除商品
     * @param goodsId
     * @return
     */
    @Override
    public boolean deleteGood(Integer goodsId) {
        UpdateWrapper<WechatBroadcastProduct> wechatBroadcastProductUpdateWrapper = new UpdateWrapper<>();
        wechatBroadcastProductUpdateWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        wechatBroadcastProductUpdateWrapper.eq("GOODS_ID",goodsId);
        wechatBroadcastProductUpdateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        boolean update = wechatBroadcastProductService.update(wechatBroadcastProductUpdateWrapper);
        logger.info("删除数据库直播间商品结果：{}",update);

        UpdateWrapper<WechatBroadcastProductMiddle> updateWrapper = new  UpdateWrapper<WechatBroadcastProductMiddle>();
        updateWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        updateWrapper.eq("GOODS_ID",goodsId);
        updateWrapper.set("DATA_STATUS", DataStatus.delete.getKey());
        boolean update1 = wechatBroadcastProductMiddleService.update(updateWrapper);
        logger.info("删除数据库直播间商品关系结果：{}",update1);


        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = GOODS_DELETE_URL + authorizerAppid.getAuthorizerAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goodsId",goodsId);
        logger.info("删除商品请求参数：{}",jsonObject);
        String data = HttpUtil.PostUrl(url, jsonObject);
        logger.info("删除商品结果：{}",data);
        jsonObject = JSONObject.parseObject(data);
        return errcode.equals(jsonObject.getString("errcode"));
    }

    /**
     * 更新商品
     * @param good
     * @return
     */
    @Override
    public boolean updateGood(Good good) {

        UpdateWrapper<WechatBroadcastProduct> wechatBroadcastProductUpdateWrapper = new UpdateWrapper<>();
        wechatBroadcastProductUpdateWrapper.eq("PLATFORM_UID", SecurityUtils.getPlatformId());
        wechatBroadcastProductUpdateWrapper.eq("GOODS_ID",good.getGoodsId());
        wechatBroadcastProductUpdateWrapper.set("NAME",good.getName());
        wechatBroadcastProductUpdateWrapper.set("PRICE_TYPE",good.getPriceType());
        wechatBroadcastProductUpdateWrapper.set("PRICE",good.getPrice());
        wechatBroadcastProductUpdateWrapper.set("PRICE2",good.getPrice2());
        wechatBroadcastProductUpdateWrapper.set("UPDATE_USER",SecurityUtils.getUserId());
        wechatBroadcastProductUpdateWrapper.set("UPDATE_NAME",SecurityUtils.getUsername());
        wechatBroadcastProductUpdateWrapper.set("UPDATE_TIME", DateUtil.date());
        boolean update = wechatBroadcastProductService.update(wechatBroadcastProductUpdateWrapper);
        logger.info("更新数据库商品结果：{}",update);


        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = GOODS_UPDATE_URL + authorizerAppid.getAuthorizerAccessToken();
        String string = JSONObject.toJSONString(good);
        JSONObject jsonObject = JSONObject.parseObject(string);
        JSONObject json = new JSONObject();
        json.put("goodsInfo",jsonObject);
        json.remove("productId");
        logger.info("更新商品请求参数：{}",json);
        String data = HttpUtil.PostUrl(url, json);
        logger.info("更新商品结果：{}",data);
        jsonObject = JSONObject.parseObject(data);
        return errcode.equals(jsonObject.getString("errcode"));
    }

    /**
     * 获取商品状态
     * @param goodsIds
     * @return
     */
    @Override
    public GoodList getGoodState(String[] goodsIds) {
        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = GETGOODSWAREHOUSE_URL + authorizerAppid.getAuthorizerAccessToken();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goods_ids",goodsIds);
        RestTemplate restTemplate = new RestTemplate();
        logger.info("获取商品状态请求参数：{}",jsonObject);
        ResponseEntity<GoodList> goodResponseEntity = restTemplate.postForEntity(url, jsonObject, GoodList.class);
        GoodList body = goodResponseEntity.getBody();
        logger.info("获取商品状态结果：{}",body.toString());
        return body;
    }

    /**
     * 获取商品列表
     * @param queryGood
     * @return
     */
    @Override
    public GoodList getGoodsList(QueryGood queryGood) {
        WechatAuthorizationInfo authorizerAppid = wechatMiniService.getAuthorizerAppid(applet);
        String url = GETAPPROVED_URL + authorizerAppid.getAuthorizerAccessToken()+"&offset="+(queryGood.getOffset() - 1) * queryGood.getLimit()+"&limit="+queryGood.getLimit()+"&status="+queryGood.getStatus();
        RestTemplate restTemplate = new RestTemplate();
        logger.info("获取商品列表请求参数：{}",url);
        ResponseEntity<GoodList> goodListResponseEntity = restTemplate.getForEntity(url, GoodList.class);
        logger.info("获取商品列表结果：{}",goodListResponseEntity.getBody().toString());
        GoodList body = goodListResponseEntity.getBody();
        if (body!=null && body.getErrcode() == 0){
            List<Good> collect = body.getGoods().stream().map(o -> {
                Good good = new Good();
                BeanUtils.copyProperties(o, good);
                good.setAudit_status(queryGood.getStatus());
                QueryWrapper<WechatBroadcastProduct> wechatBroadcastProductQueryWrapper = new QueryWrapper<>();
                wechatBroadcastProductQueryWrapper.eq("PLATFORM_UID",SecurityUtils.getPlatformId());
                wechatBroadcastProductQueryWrapper.eq("GOODS_ID",o.getGoodsId());
                WechatBroadcastProduct wechatBroadcastProduct = wechatBroadcastProductMapper.selectOne(wechatBroadcastProductQueryWrapper);
                logger.info("读取数据库缓存商品信息："+wechatBroadcastProduct);
                if (wechatBroadcastProduct != null){
                    good.setAuditId(wechatBroadcastProduct.getAuditId().toString());
                    good.setOperation("1");
                }else{
                    good.setOperation("0");
                }
                return good;
            }).collect(Collectors.toList());
            body.setGoods(collect);
        }

        return body;
    }

}
